Skip to content

fix(streaming): restore estimates when provider usage is absent - #45443

Closed
parkjohnston wants to merge 1 commit into
BerriAI:mainfrom
parkjohnston:parkjohnston-token-counting-fix
Closed

parkjohnston wants to merge 1 commit into
BerriAI:mainfrom
parkjohnston:parkjohnston-token-counting-fix

Conversation

@parkjohnston

@parkjohnston parkjohnston commented Oct 8, 2026 •

Copy link
Copy Markdown

TLDR

Problem this solves:

  • Since v1.104.0, a stream with no provider usage object is logged at 0 tokens
  • GitHub Copilot BYOK users saw real counts on v1.103.1 and zero on v1.104.2
  • The gateway's own placeholder 0/0 usage was kept as if the provider had reported it

How it solves it:

  • Hidden usage is attached to the final chunk only when some chunk reported usage
  • With nothing reported, the assembled response estimates tokens from the text, as v1.103.1 did
  • A provider that reports usage, real counts or an explicit 0, is logged as reported
  • Parametrized sync and async tests cover absent, zero, and real usage per finish shape

User Flow

Before: a developer streaming chat completions through a deployment whose backend sends no usage object sees every request logged at 0 tokens

  1. They send POST https://litellm-domain/v1/chat/completions with "stream": true and no stream_options to a model whose backend streams no usage object
  2. Content chunks stream back and the final chunk carries no usage field, the same bytes v1.103.1 returned
  3. GET https://litellm-domain/spend/logs?request_id= returns prompt_tokens: 0, completion_tokens: 0, spend: 0.0
  4. https://litellm-domain/ui/?page=logs shows the request at 0 tokens and $0, where v1.103.1 showed the estimate (16 prompt, 58 completion)

After: the same request is logged with the token estimate v1.103.1 produced

  1. They send POST https://litellm-domain/v1/chat/completions with "stream": true and no stream_options to a model whose backend streams no usage object
  2. Content chunks stream back and the final chunk carries no usage field, the same bytes v1.103.1 returned
  3. GET https://litellm-domain/spend/logs?request_id= returns prompt_tokens: 16, completion_tokens: 58 and the model's priced spend
  4. https://litellm-domain/ui/?page=logs shows those counts; a backend that reports usage, real counts or an explicit 0, is logged as reported, unchanged

Relevant issues

Fixes #45422

Affected release

regression in v1.104.0 (#42323 made the chunk builder keep the placeholder 0/0 instead of estimating); on main, #44318 (unreleased) widens it to every stream finish shape

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Both legs: one proxy booted with --num_workers 2 from the named commit on the same config and database, one virtual key per leg from POST /key/generate, every request streamed with no stream_options, and the spend row read back through GET /spend/logs?request_id=. Backend with no usage in its stream: a local Ollama 0.40.1 serving qwen3:0.6b through its OpenAI-compatible endpoint, which sends no usage object unless the request asks for it. It is registered under the nvidia_nim/ prefix, which the proxy adds no stream_options for, so the request reaches the backend with none (the same shape as any backend that ignores include_usage or a client that never sends it). Control: the same backend under the openai/ prefix, where the proxy adds include_usage and Ollama reports usage. Hosted case: NVIDIA NIM z-ai/glm-5.3-flash, a priced model whose stream carries no usage object unless asked

model_list:
  - model_name: local-qwen3
    litellm_params:
      model: nvidia_nim/qwen3:0.6b
      api_base: http://127.0.0.1:11434/v1
      api_key: ollama
      drop_params: true
  - model_name: local-qwen3-openai
    litellm_params:
      model: openai/qwen3:0.6b
      api_base: http://127.0.0.1:11434/v1
      api_key: ollama
  - model_name: nim-glm-5.3-flash
    litellm_params:
      model: nvidia_nim/z-ai/glm-5.3-flash
      api_key: os.environ/NVIDIA_NIM_API_KEY
curl -sS -N -D headers.txt http://127.0.0.1:$PORT/v1/chat/completions \
  -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
  -d '{"model":"local-qwen3","stream":true,"max_tokens":60,"messages":[{"role":"user","content":"Reply with one short sentence about the sea."}]}'
call_id=$(grep -i '^x-litellm-call-id:' headers.txt | awk '{print $2}' | tr -d '\r')
curl -sS "http://127.0.0.1:$PORT/spend/logs?request_id=$call_id" -H "Authorization: Bearer $MASTER_KEY"

GitHub Copilot CLI 1.0.94 (the reporter's client) is launched as copilot --model local-qwen3 with COPILOT_PROVIDER_BASE_URL=http://127.0.0.1:$PORT/v1, COPILOT_PROVIDER_TYPE=openai, and COPILOT_PROVIDER_API_KEY=<that leg's virtual key>, driven in a terminal with the prompt "Reply with one short sentence about the sea, no tools.", and its rows read with GET /spend/logs?api_key=

Before (4ed0267)

POST /v1/chat/completions, stream with no usage object (local-qwen3)

  1. The curl above, twice: 200, 60 SSE chunks each, 0 chunks naming usage, last data line {"id":"chatcmpl-436",...,"choices":[{"finish_reason":"length","index":0,"delta":{}}]}
  2. Spend rows chatcmpl-436 and chatcmpl-446: "prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0, "spend": 0.0

POST /v1/chat/completions, stream that reports usage (local-qwen3-openai)

  1. The same curl with "model":"local-qwen3-openai": 200, 60 chunks
  2. Spend row chatcmpl-372: "prompt_tokens": 19, "completion_tokens": 60, "total_tokens": 79

POST /v1/chat/completions, hosted NIM stream with no usage object (nim-glm-5.3-flash)

  1. The same curl with "model":"nim-glm-5.3-flash": 200, 26 chunks, 0 naming usage, last data line {"id":"chatcmpl-cf07901b-...","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
  2. Spend row chatcmpl-cf07901b-32ff-4ef9-bc37-c0f31109aca1: "prompt_tokens": 0, "completion_tokens": 0, "spend": 0.0 on a priced model

POST /v1/messages (local-qwen3)

  1. {"model":"local-qwen3","stream":true,"max_tokens":60,"messages":[...]}: 200, 63 events ending in {"type": "message_stop"}
  2. Spend row msg_0006c199-769c-4099-986d-e0394b48974d: "prompt_tokens": 16, "completion_tokens": 58 (this route estimated already)

POST /v1/responses (local-qwen3)

  1. {"model":"local-qwen3","stream":true,"max_output_tokens":60,"input":"..."}: 200, 66 events ending in response.incomplete
  2. Spend row chatcmpl-559 (call_type: aresponses): "prompt_tokens": 16, "completion_tokens": 58 (this route estimated already)

GitHub Copilot CLI through local-qwen3

  1. The prompt is answered in the pane:

pr45443-83daa6e1d9-copilot-before-4ed0267b5a.png

  1. The CLI asks for include_usage itself, so Ollama reports usage: spend row chatcmpl-138 "prompt_tokens": 5746, "completion_tokens": 105 (real counts; the zero needs a stream with no usage object)

After (83daa6e)

POST /v1/chat/completions, stream with no usage object (local-qwen3)

  1. The curl above, twice: 200, 60 SSE chunks each, 0 chunks naming usage, last data line {"id":"chatcmpl-247",...,"choices":[{"finish_reason":"length","index":0,"delta":{}}]}
  2. Spend rows chatcmpl-247 and chatcmpl-256: "prompt_tokens": 16, "completion_tokens": 58, "total_tokens": 74, the estimate v1.103.1 logged

POST /v1/chat/completions, stream that reports usage (local-qwen3-openai)

  1. The same curl with "model":"local-qwen3-openai": 200, 60 chunks
  2. Spend row chatcmpl-12: "prompt_tokens": 19, "completion_tokens": 60, "total_tokens": 79, unchanged

POST /v1/chat/completions, hosted NIM stream with no usage object (nim-glm-5.3-flash)

  1. The same curl with "model":"nim-glm-5.3-flash": 200, 16 chunks, 0 naming usage
  2. Spend row chatcmpl-155b80b0-f958-4ee3-9132-2213d93716fc: "prompt_tokens": 16, "completion_tokens": 34, "total_tokens": 50

POST /v1/messages (local-qwen3)

  1. The same request: 200, 63 events ending in {"type": "message_stop"}
  2. Spend row msg_eb530019-4127-4e90-a435-80145fbeee0d: "prompt_tokens": 16, "completion_tokens": 58, unchanged

POST /v1/responses (local-qwen3)

  1. The same request: 200, 66 events ending in response.incomplete
  2. Spend row chatcmpl-432 (call_type: aresponses): "prompt_tokens": 16, "completion_tokens": 58, unchanged

GitHub Copilot CLI through local-qwen3

  1. The prompt is answered in the pane:

pr45443-83daa6e1d9-copilot-after-83daa6e1d9.png

  1. Spend row chatcmpl-733 "prompt_tokens": 5743, "completion_tokens": 107, still the provider's reported counts

Observations from the run:

  • /v1/messages and /v1/responses estimated already on the merge base; unchanged here
  • Copilot CLI sends include_usage itself; backends honoring it never zeroed
  • NIM glm-5.3-flash honors include_usage too; zero needs a backend that does not
  • Restored count is a tokenizer estimate (16 vs reported 19 prompt); same as v1.103.1
  • Spend reads 0.0 on the local model only because it has no price

Type

🐛 Bug Fix

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

Only attach aggregated hidden usage when a stream chunk reports usage. Keep final hidden parameters registered so estimates reach callers after stream exhaustion, while preserving explicit zero and late provider counts

Adapted from Zuraiz Anjum's fix in BerriAI#44230. Adds regression coverage for sync and async streams, missing and reported usage, and separate, combined, or absent finish chunks

Co-authored-by: Zuraiz Anjum <zuraizwork@gmail.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@greptile-apps

greptile-apps Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no actionable defects were found

Summary

The PR stops adding zero usage when streaming chunks contain no reported usage. The existing completion path can then estimate counts and attach them to the last returned chunk

  • Reported usage still goes through calculate_total_usage
  • The new tests cover sync and async streams, several finish patterns, zero counts, and late usage
  • No actionable issues were found. Tests were not run

Reviews (1) · Last reviewed commit: "fix(streaming): restore estimates when p..." · Reviewed by Greptile

@codspeed

codspeed Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing parkjohnston:parkjohnston-token-counting-fix (83daa6e) with main (4ed0267)

Open in CodSpeed

@parkjohnston

Copy link
Copy Markdown
Author

Resolves #45422

@codecov

codecov Bot commented Oct 8, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@mateo-berri

Copy link
Copy Markdown
Contributor

Closed as superseded by #44230, which is merged and restores the token estimate for streams without usage. Thanks for the fix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Consumed Tokens via GitHub BYOK is not operational

2 participants